package com.heima.comment.service.Impl;


import com.heima.comment.dtos.CommentRepayDto;
import com.heima.comment.dtos.CommentRepayLikeDto;
import com.heima.comment.dtos.CommentRepaySaveDto;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentRepay;
import com.heima.comment.pojos.ApCommentRepayLike;
import com.heima.comment.service.CommentRepayService;
import com.heima.comment.vo.ApCommentRepayVo;
import com.heima.feigns.user.UserFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.threadlocal.AppThreadLocalUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentRepayServiceImpl implements CommentRepayService {


    @Autowired
    UserFeign userFeign;

    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查看更多回复内容
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDto dto) {
        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        Integer size = dto.getSize();
        if ( size == null || size <= 0) {
            dto.setSize(10);
        }
        dto.setSize(Math.min(dto.getSize(), 50));

        //查询回复列表,并已倒序排序
        List<ApCommentRepay> commentRepayList = mongoTemplate.find(
                Query.query(Criteria
                        .where("commentId").is(dto.getCommentId())
                        .and("createdTime").lt(dto.getMinDate()))
                        .limit(dto.getSize())
                        .with(Sort.by(Sort.Order.desc("createdTime"))),
                ApCommentRepay.class);

        // 获取当前用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.okResult(commentRepayList);
        }

        //如果未登录,直接返回回复列表
        ApUser apUser = userFeign.findUserById(user.getId().longValue());
        if (apUser == null) {
            return ResponseResult.okResult(commentRepayList);
        }

        //回显当前用户是否对回复点赞

        // 获取所有的回复的id
        List<String> idList = commentRepayList.stream().map(x -> x.getId()).collect(Collectors.toList());

        // 在回复点赞列表中查询
        List<ApCommentRepayLike> commentRepayLikes = mongoTemplate.find(
                Query.query(Criteria.where("authorId").is(apUser.getId())
                            .and("commentRepayId").in(idList)
                            .and("operation").is(0)
                ), ApCommentRepayLike.class);

        // 保存用户回显点赞数据集合
        List<ApCommentRepayVo> apCommentRepayVos = new ArrayList<>();

        if(commentRepayList!=null && commentRepayList.size()>0 && commentRepayLikes!=null
                && commentRepayLikes.size()>0){

            commentRepayList.forEach(x -> {

                ApCommentRepayVo apCommentRepayVo = new ApCommentRepayVo();
                BeanUtils.copyProperties(x, apCommentRepayVo);

                // 处理回显问题
                commentRepayLikes.forEach(commentRepayLike -> {
                    // 当前用户对这条评论点赞
                    if (x.getId().equals(commentRepayLike.getCommentRepayId())) {
                        apCommentRepayVo.setOperation((short) 0);
                    }
                });
                apCommentRepayVos.add(apCommentRepayVo);
            });
            return ResponseResult.okResult(apCommentRepayVos);
        }
        //4 返回结果
        return ResponseResult.okResult(commentRepayList);
    }

    /**
     * 保存回复
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {

        if (dto == null || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        String content = dto.getContent();
        if (StringUtils.isBlank(content) || content.length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //  todo 内容安全监测
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser apUser = userFeign.findUserById(user.getId().longValue());
        if (apUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setContent(content);
        apCommentRepay.setLikes(0);
        apCommentRepay.setUpdatedTime(new Date());
        mongoTemplate.save(apCommentRepay);

        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 点赞回复的评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDto dto) {

        if (dto == null || dto.getCommentRepayId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApCommentRepay commentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (commentRepay == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //查询回复的点赞是否存在
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(
                Query.query(Criteria.where("authorId").is(user.getId())
                        .and("commentRepayId").is(dto.getCommentRepayId())),
                ApCommentRepayLike.class);
        if (commentRepayLike != null && dto.getOperation().intValue() == 0
                && commentRepayLike.getOperation().intValue() == 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "无需重复点赞");
        }

        if (dto.getOperation().intValue() == 0) {

            if (commentRepayLike == null) {
                commentRepayLike = new ApCommentRepayLike();
                commentRepayLike.setAuthorId(user.getId());
                commentRepayLike.setCommentRepayId(commentRepay.getId());
            }
            commentRepayLike.setOperation(dto.getOperation());
            mongoTemplate.save(commentRepayLike);


            commentRepay.setLikes(commentRepay.getLikes() + 1);
            mongoTemplate.save(commentRepay);




        } else {
            commentRepayLike.setOperation((short) 1);
            mongoTemplate.save(commentRepayLike);



            commentRepay.setLikes(  (commentRepay.getLikes() - 1) < 0 ? 0: commentRepay.getLikes() - 1);
            mongoTemplate.save(commentRepay);
        }


        Map<String, Integer> resultMap = new HashMap<>();
        resultMap.put("likes", commentRepay.getLikes());
        return ResponseResult.okResult(resultMap);
    }
}
